package lk.icta.core.dao.impl;

import lk.icta.common.dao.PreloadableDAO;
import lk.icta.common.dao.impl.BaseDAO;
import lk.icta.core.dao.WorkflowDAO;
import lk.icta.core.entity.WorkflowItem;
import lk.icta.core.entity.WorkflowTask;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import javax.persistence.Query;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.TreeMap;

public class WorkflowDAOImpl extends BaseDAO implements WorkflowDAO, PreloadableDAO {

    private final Map<Integer, WorkflowItem> workflowItemList = new HashMap<Integer, WorkflowItem>();
  //  private final Map<Integer, WorkflowItem> workflowStartItemList = new HashMap<Integer, WorkflowItem>();

    /**
     * Loads all values from the database table into a cache
     */
    @Transactional(propagation = Propagation.NEVER, readOnly = true)
    public void preload() {

        Query query = em.createQuery("SELECT d FROM WorkflowItem d");
        List<WorkflowItem> results = query.getResultList();

        for (WorkflowItem workflowItem : results) {
            //put all item to list
            workflowItemList.put(workflowItem.getId(), workflowItem);
            //initiate seperate workflows/ alienation methods
           /* if (workflowItem.getId() == START_NODE) {

                workflowStartItemList.put(workflowItem.getAlienationMethod().getId(), workflowItem);
            }  */
        }

        logger.debug("Caching : {} workflow Items from the database", results.size());
    }

    public WorkflowItem getWorkflowItemById(int id) {
        return workflowItemList.get(id);
    }

   /* public List<Integer> getWorkflowItemsByTaskAndRole(WorkflowTask workflowTask, String role) {
        List<Integer> workflowItemList = null;
        return workflowItemList;
    }
*/
    public Map<Integer, WorkflowItem> getAllWorkflowItems() {
        return workflowItemList;
    }

 /*   public WorkflowItem getStartItemOfWorkflow(int alienationMethodId) {
        return workflowStartItemList.get(alienationMethodId);
    }*/

}
